package com.webcams.ui.settings;

import java.util.ArrayList;

import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckedTextView;
import android.widget.TextView;

import com.webcams.core.settings.BooleanSetting;
import com.webcams.core.settings.Setting;
import com.webcams.core.settings.SettingsManager;

public class SettingsUI extends ListActivity {

	@Override
	public void onCreate(Bundle state) {

		super.onCreate(state);

		final SettingsManager settings = SettingsManager.getInstance(this);

		MyCustomAdapter mAdapter = new MyCustomAdapter();
		for (Setting s : settings) {
			mAdapter.addItem(s);
		}
		setListAdapter(mAdapter);
	}

	private class MyCustomAdapter extends BaseAdapter {

		private LayoutInflater mInflater;
		private ArrayList<Setting> mData = new ArrayList<Setting>();

		public MyCustomAdapter() {
			mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		public void addItem(final Setting item) {
			mData.add(item);
			notifyDataSetChanged();
		}

		@Override
		public int getCount() {
			return mData.size();
		}

		@Override
		public Object getItem(int position) {
			return mData.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			
			if (convertView == null) {
				holder = new ViewHolder();

				if(mData.get(position) instanceof BooleanSetting) {
					convertView = mInflater.inflate(android.R.layout.simple_list_item_multiple_choice, parent, false);
					holder.textView = (CheckedTextView)convertView;
					
					final BooleanSetting bs = (BooleanSetting)mData.get(position);
					((CheckedTextView)holder.textView).setChecked(bs.getValue());
					
					holder.textView.setOnClickListener(new OnClickListener(){
						@Override
						public void onClick(View v) {
							if(v instanceof CheckedTextView) {
								((CheckedTextView)v).toggle();
								bs.setValue(((CheckedTextView)v).isChecked());
							}
						}
					});
				} else {
					convertView = mInflater.inflate(android.R.layout.simple_list_item_1, parent, false);
					holder.textView = (CheckedTextView)convertView;
				}
				
				holder.textView.setText(mData.get(position).getName());
				convertView.setTag(holder);

			} else {
				holder = (ViewHolder)convertView.getTag();
			}
			
			return convertView;
		}

	}
	public static class ViewHolder {
		public TextView textView;
	}
}
